package com.mz.ozy.activity.shop;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;

import com.mz.ozy.R;
import com.mz.ozy.activity.me.AddressActivity;
import com.mz.ozy.activity.me.MyOrderActivity;
import com.mz.ozy.activity.me.MyOrderFragment;
import com.mz.ozy.activity.me.PayPwdActivity;
import com.mz.ozy.base.BaseActivity;
import com.mz.ozy.bean.AddressBean;
import com.mz.ozy.bean.CarInfoBean;
import com.mz.ozy.bean.EventBean;
import com.mz.ozy.bean.FirmOrderBean;
import com.mz.ozy.bean.FreightBean;
import com.mz.ozy.bean.FreightMapBean;
import com.mz.ozy.bean.NetBean;
import com.mz.ozy.bean.OrderBean;
import com.mz.ozy.bean.VoucherBean;
import com.mz.ozy.constants.Constants;
import com.mz.ozy.mvp.presenter.FirmOrderPresenter;
import com.mz.ozy.mvp.view.FirmOrderContract;
import com.mz.ozy.utils.CalendarUtils;
import com.mz.ozy.utils.PayManager;
import com.mz.ozy.utils.ToastUtils;
import com.mz.ozy.utils.Utils;
import com.mz.ozy.utils.glideUtils.GlideUtils;
import com.mz.ozy.widget.dialog.PayActivityDialog;
import com.mz.ozy.widget.dialog.PayPassDialog;
import com.mz.ozy.widget.dialog.PayPassView;
import com.mz.ozy.widget.dialog.PaySelectDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2018/11/21.
 */

public class FirmOrderActivity1 extends BaseActivity<FirmOrderContract.View, FirmOrderPresenter> implements FirmOrderContract.View {

    @BindView(R.id.tv_name)
    TextView mTvName;
    @BindView(R.id.tv_empty)
    TextView mTvEmpty;
    @BindView(R.id.tv_default)
    TextView mTvDefault;
    @BindView(R.id.tv_mobile)
    TextView mTvMobile;
    @BindView(R.id.tv_address)
    TextView mTvAddress;
    @BindView(R.id.rv_goods_list)
    LinearLayout mRvGoodsList;
    @BindView(R.id.tv_presale_type)
    TextView mTvPresaleType;
    @BindView(R.id.tv_presale_time)
    TextView mTvPresaleTime;
    @BindView(R.id.ll_goods_content)
    LinearLayout mLlGoodsContent;
    @BindView(R.id.tv_goods_count)
    TextView mTvGoodsCount;
    @BindView(R.id.ll_user_info)
    LinearLayout mLlUserInfo;
    @BindView(R.id.tv_freight_count)
    TextView mTvFreightCount;
    @BindView(R.id.tv_real_payment)
    TextView mTvRealPayment;
    @BindView(R.id.iv_firm_right)
    ImageView mIvFirmRight;
    @BindView(R.id.iv_firm_location)
    ImageView mIvFirmLocation;
    @BindView(R.id.et_remark)
    EditText mEtRemark;
    @BindView(R.id.tv_express_delivery)
    TextView mTvExpressDelivery;
    @BindView(R.id.tv_full_reduction)
    TextView mTvReduction;
    @BindView(R.id.tv_activity_price)
    TextView mTvActivityPrice;
    @BindView(R.id.tv_order_integral)
    TextView mTvOrderIntegral;
    @BindView(R.id.tv_deduct_amt)
    TextView mTvDeductAmt;
    @BindView(R.id.iv_select)
    ImageView mIvSelect;
    @BindView(R.id.ll_yh_view)
    LinearLayout llYhView;
    @BindView(R.id.rl_integral_balance)
    RelativeLayout rlIntegralBalance;
    @BindView(R.id.rl_deduct)
    RelativeLayout rlDeduct;
    private FirmOrderBean mFirmOrderBean;
    private List<FirmOrderBean.ProductMapBean> goodsList;
    private double mTotalPriceW;
    private int mGoodsNum;
    private double mTotalPrice;
    private double mTotalMarketPrice;
    private String mCid;
    private String mGid;//商品id  详情发起的立即购买
    private String mAid;
    private int mArea0id;
    private int mArea1id;
    private int mArea2id;
    private double mFreight = 0.00;
    private long curTime;
    private boolean hasAddress = false;
    private boolean hasWeightActivity = false;
    private boolean hasDefaultAddress = false;
    private int payType;
    private PayManager mPayManager;
    private List<VoucherBean.AcListBean> mActList;
    private PayActivityDialog activityDialog;
    private VoucherBean.AcListBean acListBean;
    private boolean isDeduct = false;
    private boolean isDeIntegral = false;
    private double deductionIntegral;
    private double dkAmt;
    private String startTime = "";
    private Map<Integer, FreightMapBean> mFreightMap = new HashMap<>();
    private int tag;

    /**
     * @param context
     * @param firmOrderBean 订单信息
     * @param cid           购物车Id
     * @param gid           商品id
     */
    public static void start(Context context, FirmOrderBean firmOrderBean, String cid, String gid, int tag) {
        Intent starter = new Intent(context, FirmOrderActivity1.class);
        starter.putExtra("firmOrderBean", firmOrderBean);
        starter.putExtra("cid", cid);
        starter.putExtra("gid", gid);
        starter.putExtra("tag", tag);
        context.startActivity(starter);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_firm_order1);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        initData();
        initTitle();
        init();
        reloadTotalPrice();
        queryRedeemVoucher();
    }

    private void reloadTotalPrice() {
        if (hasAddress) {
            mTotalPriceW = mTotalPrice + mFreight;
        } else {
            mTotalPriceW = mTotalPrice;
        }
        mTotalPriceW = mTotalPriceW - preferentialPrice;
        if (isDeduct) {
            mTotalPriceW = mTotalPriceW - dkAmt;
        }
        mTvRealPayment.setText(getPrice(mTotalPriceW));
    }

    private void queryFreight(String activId) {
        List<Map<String, String>> mapList = new ArrayList<>();
        final List<FirmOrderBean.ProductMapBean> carList = goodsList;
        if (carList != null && carList.size() > 0) {
            for (int index = 0; index < carList.size(); index++) {
                final FirmOrderBean.ProductMapBean productMapBean = carList.get(index);
                Map<String, String> map = new HashMap<>();
                map.put("productId", String.valueOf(productMapBean.getProduct_id()));
                map.put("attributeId", String.valueOf(productMapBean.getAttribute_id()));
                map.put("freightId", productMapBean.getFreightid() + "");
                map.put("num", productMapBean.getNum() + "");
                mapList.add(map);
            }
        }
        mPresenter.queryFreight(this, activId, mapList.toString());
    }

    private void queryRedeemVoucher() {
        List<Map<String, String>> mapList = new ArrayList<>();
        final List<FirmOrderBean.ProductMapBean> carList = goodsList;
        if (carList != null && carList.size() > 0) {
            for (int index = 0; index < carList.size(); index++) {
                final FirmOrderBean.ProductMapBean productMapBean = carList.get(index);
                Map<String, String> map = new HashMap<>();
                map.put("productId", String.valueOf(productMapBean.getProduct_id()));
                map.put("attributeId", String.valueOf(productMapBean.getAttribute_id()));
                map.put("freightId", productMapBean.getFreightid() + "");
                map.put("num", productMapBean.getNum() + "");
                mapList.add(map);
            }
        }
        mPresenter.queryVoucher(this, mapList.toString());
    }

    protected void onResume() {
        super.onResume();
        PayManager.pay_from = 2;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventBean event) {
        //刷新购物车
        if ((event.getCode() == Constants.EventCode.WX_PAY_SUCCESS || event.getCode() == Constants.EventCode.ALIPAY_PAY_SUCCESS)
                && PayManager.pay_from == 2) {
            ToastUtils.showToast("支付成功");
            finish();
            MyOrderActivity.start(this, MyOrderFragment.TYPE_SEND);
        }
        if ((event.getCode() == Constants.EventCode.JUMP_PAY_PWD)) {
            startActivity(new Intent(this, PayPwdActivity.class));
        }
        if (event.getCode() == Constants.EventCode.CHANGE_DEFAULT_ADDRESS) {
            final AddressBean addressBean = (AddressBean) event.getData();
            reLoadAddressMap(addressBean);
            if (mAid.equals("-1")) {
                hasDefaultAddress = true;
                reLoadCurAddress(addressBean);
            } else {
                if (mAid.equals(addressBean.getId())) {
                    mTvDefault.setVisibility(View.VISIBLE);
                } else {
                    mTvDefault.setVisibility(View.GONE);
                }
            }
        }
        if (event.getCode() == Constants.EventCode.EDIT_ADDRESS) {
            final AddressBean addressBean = (AddressBean) event.getData();
            if (addressBean.getId() == mFirmOrderBean.getShaddressMap().getId()) {
                reLoadAddressMap(addressBean);
            }
            reLoadCurAddress(addressBean);
        }
        if (event.getCode() == Constants.EventCode.DELETE_DEFAULT_ADDRESS) {
            hasDefaultAddress = false;
            if (mAid.equals(mFirmOrderBean.getShaddressMap().getId() + "")) {
                reLoadNoAddress();
            }
        } else if (event.getCode() == Constants.EventCode.DELETE_ADDRESS) {
            if (hasDefaultAddress) {
                reLoadDefaultAddressAndFreight();
            } else {
                reLoadNoAddress();
            }
        }
    }

    private void reLoadDefaultAddressAndFreight() {
        reLoadDefaultAddress();
        hasAddress = true;
        reLoadFreight();
        reloadTotalPrice();
    }

    private void reLoadCurAddress(AddressBean bean) {
        mLlUserInfo.setVisibility(View.VISIBLE);
        mTvEmpty.setVisibility(View.GONE);
        mIvFirmRight.setImageResource(R.mipmap.firm_right_arrow);
        mIvFirmLocation.setVisibility(View.VISIBLE);
        mTvName.setText(bean.getConsignee());
        final String contactnumber = bean.getContactnumber();
        final String phonestr = contactnumber.substring(0, 3) + "****" + contactnumber.substring(contactnumber.length() - 4);
        mTvMobile.setText(phonestr);
        if (1 == bean.getIsdefault()) {
            mTvDefault.setVisibility(View.VISIBLE);
        } else {
            mTvDefault.setVisibility(View.GONE);
        }
        String address = "";
        if (bean.getArea0id().equals(bean.getArea1id())) {
            address = bean.getArea1name() + bean.getArea2name() + bean.getXxaddress();
        } else {
            address = bean.getArea0name() + bean.getArea1name() + bean.getArea2name() + bean.getXxaddress();
        }
        mTvAddress.setText(address);
        mAid = String.valueOf(bean.getId());
        mArea0id = Integer.parseInt(bean.getArea0id());
        mArea1id = Integer.parseInt(bean.getArea1id());
        mArea2id = Integer.parseInt(bean.getArea2id());
        hasAddress = true;
        reLoadFreight();
        reloadTotalPrice();
    }

    private void reLoadAddressMap(AddressBean addressBean) {
        mFirmOrderBean.getShaddressMap().setId(addressBean.getId());
        mFirmOrderBean.getShaddressMap().setArea0id(Integer.parseInt(addressBean.getArea0id()));
        mFirmOrderBean.getShaddressMap().setArea1id(Integer.parseInt(addressBean.getArea1id()));
        mFirmOrderBean.getShaddressMap().setArea2id(Integer.parseInt(addressBean.getArea2id()));
        mFirmOrderBean.getShaddressMap().setArea0name(addressBean.getArea0name());
        mFirmOrderBean.getShaddressMap().setArea1name(addressBean.getArea1name());
        mFirmOrderBean.getShaddressMap().setArea2name(addressBean.getArea2name());
        mFirmOrderBean.getShaddressMap().setXxaddress(addressBean.getXxaddress());
        mFirmOrderBean.getShaddressMap().setContactnumber(addressBean.getContactnumber());
        mFirmOrderBean.getShaddressMap().setConsignee(addressBean.getConsignee());
        mFirmOrderBean.getShaddressMap().setIsdefault(addressBean.getIsdefault());
    }

    private void reLoadNoAddress() {
        mLlUserInfo.setVisibility(View.GONE);
        mTvAddress.setText("");
        mIvFirmLocation.setVisibility(View.GONE);
        mIvFirmRight.setImageResource(R.mipmap.empty_right_arrow);
        mTvEmpty.setVisibility(View.VISIBLE);
        hasAddress = false;
        mAid = "-1";
        reLoadFreight();
        reloadTotalPrice();
    }

    private void initData() {
        mFirmOrderBean = (FirmOrderBean) getIntent().getSerializableExtra("firmOrderBean");
        mCid = getIntent().getStringExtra("cid");
        mGid = getIntent().getStringExtra("gid");
        tag = mFirmOrderBean.getCarList().get(0).getProducttype();

        String price = mFirmOrderBean.getCarList().get(0).getPrice();
        if (Double.parseDouble(price) == 0.00) {
            //积分商品
            rlDeduct.setVisibility(View.GONE);
        }

        if (tag == Constants.OB_TYPE) {
            rlIntegralBalance.setVisibility(View.GONE);
            rlDeduct.setVisibility(View.GONE);

        }
        if (mFirmOrderBean == null && TextUtils.isEmpty(mCid)) {
            ToastUtils.showToast("数据有误");
            finish();
        }
        goodsList = mFirmOrderBean.getCarList();
        mArea0id = mFirmOrderBean.getShaddressMap().getArea0id();
        mArea1id = mFirmOrderBean.getShaddressMap().getArea1id();
        mArea2id = mFirmOrderBean.getShaddressMap().getArea2id();
        if (mArea0id == 0 && mArea1id == 0 && mArea2id == 0) {
            hasAddress = false;
        } else {
            hasAddress = true;
        }
        mPayManager = new PayManager(this);
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        Date curDate = cal.getTime();
        curTime = curDate.getTime();
    }

    private boolean existFreightItem = true;

    private double proccessCarFreight() {
        double curFreight = 0.0;
        mFreightMap.clear();
        existFreightItem = true;
        if (goodsList != null && goodsList.size() > 0) {
            for (FirmOrderBean.ProductMapBean tmpMapBean : goodsList) {
                tmpMapBean.setFreightid(0);
                tmpMapBean.setType(1);
                tmpMapBean.setAmount("0.00");
                tmpMapBean.setContinuation("0.00");
                if (tmpMapBean.getFreightList() != null && tmpMapBean.getFreightList().size() > 0) {
                    boolean tmpExist = false;
                    for (FirmOrderBean.FreightMapBean freightMapBean : tmpMapBean.getFreightList()) {
                        boolean isSame = compareFreight(freightMapBean.getArea());
                        if (isSame) {
                            tmpExist = true;
                            tmpMapBean.setFreightid(freightMapBean.getId());
                            tmpMapBean.setType(freightMapBean.getType());
                            tmpMapBean.setAmount(freightMapBean.getAmount());
                            tmpMapBean.setContinuation(freightMapBean.getContinuation());
                            break;
                        }
                    }
                    if (!tmpExist) {
                        existFreightItem = false;
                    }
                    double tmpFreight = 0.0;
                    if (tmpMapBean.getType() == 0) {
                        tmpFreight = Double.parseDouble(tmpMapBean.getAmount());
                        if (tmpMapBean.getNum() > 1) {
                            final int spaceNum = tmpMapBean.getNum() - 1;
                            tmpFreight = tmpFreight + Double.parseDouble(tmpMapBean.getContinuation()) * spaceNum;
                        }
                    } else if (tmpMapBean.getType() == 1) {
                        tmpFreight = 0.0;
                    } else {
                        final String ggweight = tmpMapBean.getFreWeight();
                        if (TextUtils.isEmpty(ggweight)) {
                            tmpFreight = 0.0;
                        } else {
                            double totalWeight = Double.parseDouble(ggweight) * tmpMapBean.getNum();
                            if (mFreightMap.get(tmpMapBean.getFreightid()) != null) {
                                final FreightMapBean freightMapBean = mFreightMap.get(tmpMapBean.getFreightid());
                                freightMapBean.setTotalWeight(totalWeight + freightMapBean.getTotalWeight());
                            } else {
                                FreightMapBean freightMapBean = new FreightMapBean(totalWeight, tmpMapBean.getAmount(), tmpMapBean.getContinuation());
                                mFreightMap.put(tmpMapBean.getFreightid(), freightMapBean);
                            }
                        }

                    }
                    curFreight += tmpFreight;
                }
            }
            if (!mFreightMap.isEmpty()) {
                for (Map.Entry<Integer, FreightMapBean> freightEntry : mFreightMap.entrySet()) {
                    double tmpFreight = 0.0;
                    final FreightMapBean entryValue = freightEntry.getValue();
                    if (entryValue.getTotalWeight() <= 1.0) {
                        tmpFreight = Double.parseDouble(entryValue.getFreight());
                    } else {
                        tmpFreight = Double.parseDouble(entryValue.getFreight());
                        double spaceWeight = entryValue.getTotalWeight() - 1.0;
                        final double times = Math.ceil(spaceWeight / 1.0);
                        tmpFreight = tmpFreight + Double.parseDouble(entryValue.getContinuation()) * times;
                    }
                    curFreight += tmpFreight;
                }
            }

        }
        return curFreight;
    }

    private boolean compareFreight(String area) {
        final String[] areaArr = area.split(",");
        boolean oneSame = false;
        boolean twoSame = false;
        boolean threeSame = false;
        String oneArea = mArea0id + "";
        String twoArea = mArea1id + "";
        String threeArea = mArea2id + "";
        if (areaArr != null && areaArr.length > 0) {
            for (String tmparea : areaArr) {
                if (oneArea.equals(tmparea)) {
                    oneSame = true;
                }
                if (twoArea.equals(tmparea)) {
                    twoSame = true;
                }
                if (threeArea.equals(tmparea)) {
                    threeSame = true;
                }
                if (oneSame == true || twoSame == true || threeSame == true) {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public void onSubmitSuccess(OrderBean orderBean) {
//        OrderPayActivity.start(this, orderBean.getOrderNo());
//        EventBus.getDefault().post(new EventBean(Constants.EventCode.REFRESH_CAR, null));
//        finish();
        Log.e("TAG", "onSubmitSuccess");
        EventBus.getDefault().post(new EventBean(Constants.EventCode.REFRESH_CAR, null));
        showSportsHarmDialog(orderBean);
    }

    @Override
    public void onSubmitJfSuccess(OrderBean orderBean) {
        Log.e("TAG", "onSubmitJfSuccess");
        EventBus.getDefault().post(new EventBean(Constants.EventCode.REFRESH_CAR, null));
        showSportsHarmDialog(orderBean);
    }

    @Override
    public void handleFailResponse(NetBean bean) {
        super.handleFailResponse(bean);
        if (Constants.TransCode.TransCode10117.equals(bean.getTransCode())) {
            finish();
            MyOrderActivity.start(this, MyOrderFragment.TYPE_PAY);
        }
    }

    @Override
    public void onPaySuccess(JSONObject orderBean) {
        if (payType == 0) { //余额支付
            ToastUtils.showToast("支付成功");
            finish();
            MyOrderActivity.start(this, MyOrderFragment.TYPE_SEND);
        } else if (payType == 2) {  //微信支付
            mPayManager.handleWxPay(orderBean);
        } else if (payType == 1) {  //支付宝支付
            mPayManager.handleAliPay(orderBean.optString("zfb"));
        } else if (payType == 3) {
            //积分支付
            ToastUtils.showToast("支付成功");
            finish();
            MyOrderActivity.start(this, MyOrderFragment.TYPE_SEND);
        }
    }

    @Override
    public void onPayError(String s) {
        Log.e("TAG", "onPayError");
        finish();
        MyOrderActivity.start(this, MyOrderFragment.TYPE_PAY);
    }

    //查询兑换券
    @Override
    public void queryVoucherSuccess(VoucherBean voucherBean) {
        deductionIntegral = Double.parseDouble(voucherBean.getDeductionIntegral());
        dkAmt = Double.parseDouble(voucherBean.getDkAmt());
        if (deductionIntegral == 0.0) {
            isDeIntegral = false;
        } else {
            isDeIntegral = true;
            mTvDeductAmt.setText(Utils.subTwoNumber(deductionIntegral) + "积分");
        }
        final List<VoucherBean.AcListBean> aclist = voucherBean.getAclist();
        if (aclist != null) {
            this.mActList = aclist;
            acListBean = mActList.get(0);
            mTvReduction.setText(acListBean.getName() + ">");
            mTvReduction.setTextColor(ContextCompat.getColor(this, R.color.c_73b21a));
            loadPreferPrice();
            if (hasWeightActivity) {
                queryFreight(acListBean.getId() + "");
            } else {
                if (tag == Constants.OB_TYPE) {
                    mTvActivityPrice.setText("优惠 -" + Utils.subTwoNumber(preferentialPrice) + "欧花");

                } else {
                    mTvActivityPrice.setText("优惠 -¥" + Utils.subTwoNumber(preferentialPrice));

                }

                reloadTotalPrice();
            }
        }
    }

    @Override
    public void queryFreightSuccess(FreightBean orderBean) {
        final String yAmount = orderBean.getyAmount();
        double curFreight = Double.parseDouble(yAmount);
        preferentialPrice = mFreight - curFreight;
        mTvActivityPrice.setText("优惠 -¥" + Utils.subTwoNumber(preferentialPrice));
        reloadTotalPrice();
    }

    private double preferentialPrice = 0.0;

    private void loadPreferPrice() {
        if (acListBean != null) {
            hasWeightActivity = false;
            if (acListBean.getType() == 0) {
                final double activityPrice = Double.parseDouble(acListBean.getActivity_price());
                final double acAmt = Double.parseDouble(acListBean.getAcAmt());
                if (acAmt >= activityPrice) {
                    preferentialPrice = Double.parseDouble(acListBean.getPreferential_price());
                }
            } else if (acListBean.getType() == 1) {
                final double acAmt = Double.parseDouble(acListBean.getAcAmt());
                final int times = (int) (acAmt / Double.parseDouble(acListBean.getActivity_price()));
                preferentialPrice = Double.parseDouble(acListBean.getPreferential_price()) * times;
            } else {
                final double activityPrice = Double.parseDouble(acListBean.getActivity_price());
                final double acAmt = Double.parseDouble(acListBean.getAcAmt());
                if (acAmt >= activityPrice) {
                    hasWeightActivity = true;
                }
            }
        }
    }

    private void showPopListView() {
        activityDialog = new PayActivityDialog(this);
        activityDialog.setData(mActList, acListBean.getId());
        activityDialog.setOnDialogListener(new PayActivityDialog.onDialogListener() {
            @Override
            public void onConfirm(VoucherBean.AcListBean item) {
                acListBean = item;
                mTvReduction.setText(item.getName() + ">");
                loadPreferPrice();
                if (hasWeightActivity) {
                    queryFreight(acListBean.getId() + "");
                } else {
                    mTvActivityPrice.setText("优惠 -¥" + Utils.subTwoNumber(preferentialPrice));
                    reloadTotalPrice();
                }
            }
        });
        activityDialog.toggleDialog();
    }

    @Override
    public void onSubmitError(String msg) {
//         ToastUtils.showToast(msg);
        Log.e("TAG", "onSubmitError==" + msg);
    }

    private void init() {
        tvCenterTitle.setText("确认订单");
        mAid = "-1";
        if (TextUtils.isEmpty(mFirmOrderBean.getShaddressMap().getConsignee())) {
            hasDefaultAddress = false;
            mLlUserInfo.setVisibility(View.GONE);
            mTvAddress.setText("");
            mIvFirmLocation.setVisibility(View.GONE);
            mTvEmpty.setVisibility(View.VISIBLE);
            mIvFirmRight.setImageResource(R.mipmap.empty_right_arrow);
        } else {
            hasDefaultAddress = true;
            mTvEmpty.setVisibility(View.GONE);
            mIvFirmRight.setVisibility(View.VISIBLE);
            mIvFirmLocation.setVisibility(View.VISIBLE);
            reLoadDefaultAddress();
        }
        processCarList();
        final CarInfoBean carInfoBean = getCarInfoBean(goodsList);
        mTotalPrice = carInfoBean.getTotalPrice();
        mTotalMarketPrice = carInfoBean.getTotalMarketPrice();
        mGoodsNum = carInfoBean.getNum();

        if (mFirmOrderBean.getKtmap() != null) {
            final String integral = mFirmOrderBean.getKtmap().getIntegral();
            mTvOrderIntegral.setText(Utils.decimalUtils(integral, 2));
        }
    }

    private void reLoadDefaultAddress() {
        mTvName.setText(mFirmOrderBean.getShaddressMap().getConsignee());
        final String contactnumber = mFirmOrderBean.getShaddressMap().getContactnumber();
        final String phonestr = contactnumber.substring(0, 3) + "****" + contactnumber.substring(contactnumber.length() - 4);
        mTvMobile.setText(phonestr);
        mAid = String.valueOf(mFirmOrderBean.getShaddressMap().getId());
        mArea0id = mFirmOrderBean.getShaddressMap().getArea0id();
        mArea1id = mFirmOrderBean.getShaddressMap().getArea1id();
        mArea2id = mFirmOrderBean.getShaddressMap().getArea2id();
        String address = "";
        if (mArea0id == mArea1id) {
            address = mFirmOrderBean.getShaddressMap().getArea1name() + mFirmOrderBean.getShaddressMap().getArea2name() + mFirmOrderBean.getShaddressMap().getXxaddress();
        } else {
            address = mFirmOrderBean.getShaddressMap().getArea0name() + mFirmOrderBean.getShaddressMap().getArea1name() + mFirmOrderBean.getShaddressMap().getArea2name() + mFirmOrderBean.getShaddressMap().getXxaddress();
        }
        mTvAddress.setText(address);
        if (1 == mFirmOrderBean.getShaddressMap().getIsdefault()) {
            mTvDefault.setVisibility(View.VISIBLE);
        } else {
            mTvDefault.setVisibility(View.GONE);
        }
    }

    private CarInfoBean getCarInfoBean(List<FirmOrderBean.ProductMapBean> carList) {
        double totalPrice = 0.00;
        double totalMarketPrice = 0.00;
        int num = 0;
        for (FirmOrderBean.ProductMapBean mapBean : carList) {
            num += mapBean.getNum();
            double price = 0.00;
            if (!TextUtils.isEmpty(mapBean.getPrice())) {
                price = Double.parseDouble(mapBean.getPrice());
            }
            double marketPrice = 0.00;
            if (!TextUtils.isEmpty(mapBean.getMarketPrice())) {
                marketPrice = Double.parseDouble(mapBean.getMarketPrice());
            }
            totalPrice = totalPrice + price * mapBean.getNum();
            totalMarketPrice = totalMarketPrice + marketPrice * mapBean.getNum();
        }
        return new CarInfoBean(totalPrice, totalMarketPrice, num);
    }

    private void processCarList() {
        if (goodsList != null && goodsList.size() > 0) {
            FirmOrderBean.ProductMapBean productMapBean = goodsList.get(0);
            if (!TextUtils.isEmpty(productMapBean.getStarttime())) {
                Date date = null;
                try {
                    date = CalendarUtils.string2Date(productMapBean.getStarttime());
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                if (curTime < date.getTime()) {
                    startTime = productMapBean.getStarttime();
                } else {
                    startTime = "";
                }
            } else {
                startTime = "";
            }
            if (TextUtils.isEmpty(startTime)) {

                if (productMapBean.getProducttype() == 1) {
                    mTvPresaleType.setText("欧花商品");

                } else {
                    mTvPresaleType.setText("商品清单");

                }
                mTvPresaleTime.setVisibility(View.GONE);
            } else {
                mTvPresaleType.setText("预售商品");
                mTvPresaleTime.setVisibility(View.VISIBLE);
                mTvPresaleTime.setText("开售时间" + CalendarUtils.getFormatDate(startTime));
            }
            processGoodsList();
        }
    }

    private void processGoodsList() {
        if (goodsList.size() == 0) {
            mLlGoodsContent.setVisibility(View.GONE);
        } else {
            for (FirmOrderBean.ProductMapBean productMapBean : goodsList) {
                final View submitOrderView = View.inflate(this, R.layout.item_submit_order_view, null);
                processSubmitOrderView(submitOrderView, mRvGoodsList, productMapBean);
            }
            final CarInfoBean carInfoBean = getCarInfoBean(goodsList);
            //共多少件
            mTvGoodsCount.setText("共" + carInfoBean.getNum() + "件  商品金额:");
            mTvFreightCount.setText(getPrice(carInfoBean));
            setExpressDelivery();
        }
    }

    private void setExpressDelivery() {
        if (!hasAddress) {
            mTvExpressDelivery.setText("运费 ¥0.0");
        } else {
            mFreight = proccessCarFreight();
            if (mFreight != 0.00) {
                mTvExpressDelivery.setText("运费 ¥" + Utils.subTwoNumber(mFreight));
            } else {
                if (existFreightItem) {
                    mTvExpressDelivery.setText("包邮");
                } else {
                    mTvExpressDelivery.setText("运费 ¥0.0");
                }
            }
        }

    }

    private void processSubmitOrderView(View submitOrderView, LinearLayout rvGoodsList, FirmOrderBean.ProductMapBean productMapBean) {
        rvGoodsList.addView(submitOrderView);
        ImageView ivIcon = submitOrderView.findViewById(R.id.iv_only_goods_icon);
        String imgUrl = "";
        if (!TextUtils.isEmpty(productMapBean.getImg_zt())) {
            final String[] img_arr = productMapBean.getImg_zt().trim().split(",");
            if (img_arr.length > 0) {
                imgUrl = img_arr[0];
            }
        } else if (!TextUtils.isEmpty(productMapBean.getImgZt())) {
            final String[] img_arr = productMapBean.getImgZt().trim().split(",");
            if (img_arr.length > 0) {
                imgUrl = img_arr[0];
            }
        }
        GlideUtils.loadRoundImg(this, ivIcon, imgUrl, R.mipmap.default_foods_icon, 4);
        TextView goodsTitle = submitOrderView.findViewById(R.id.tv_only_goods_title);
        if (!TextUtils.isEmpty(productMapBean.getTradename())) {
            goodsTitle.setText(productMapBean.getTradename());
        } else {
            goodsTitle.setText(productMapBean.getProductName());
        }
        TextView goodsinfo = submitOrderView.findViewById(R.id.tv_only_goods_info);
        goodsinfo.setText(productMapBean.getgName());
        TextView tvPrice = submitOrderView.findViewById(R.id.tv_goods_price);
        tvPrice.setText(getPrice(productMapBean));
        TextView tvCount = submitOrderView.findViewById(R.id.tv_count);
        tvCount.setText("×" + productMapBean.getNum());
    }

    @NotNull
    private String getPrice(CarInfoBean item) {
        String price = "";
        if (item.getTotalPrice() != 0.00) {
            price += "¥";
            price += Utils.subTwoNumber(item.getTotalPrice());
        }
        if (item.getTotalMarketPrice() != 0.00) {
            if (!TextUtils.isEmpty(price)) {
                price += "+";
                price += Utils.subTwoNumber(item.getTotalMarketPrice());
                price += "积分";
            } else {
                price += Utils.subTwoNumber(item.getTotalMarketPrice());
                price += "积分";
            }
        }
        if (TextUtils.isEmpty(price)) {
            price = "¥0.00";
        }
        if (tag == Constants.OB_TYPE) {
            return price.replace("¥", "") + "欧花";
        }
        return price;
    }

    @NotNull
    private String getPrice(FirmOrderBean.ProductMapBean item) {
        String price = "";
        if (!TextUtils.isEmpty(item.getPrice()) && Double.parseDouble(item.getPrice()) != 0.00) {
            price += "¥";
            price += item.getPrice();
        }
        if (!TextUtils.isEmpty(item.getMarketPrice()) && Double.parseDouble(item.getMarketPrice()) != 0.00) {
            if (!TextUtils.isEmpty(price)) {
                price += "+";
                price += item.getMarketPrice();
                price += "积分";
            } else {
                price += item.getMarketPrice();
                price += "积分";
            }
        }
        if (TextUtils.isEmpty(price)) {
            price = "¥0.00";
        }
        if (tag == Constants.OB_TYPE) {
            return price.replace("¥", "") + "欧花";
        }
        return price;
    }

    private String getPriceSpace(double totalPrice) {
        String price = "";
//        if (mTotalMarketPrice == 0.00) {
        if (totalPrice != 0.00) {
            price += Utils.subTwoNumber(totalPrice);
        }
//        }

        if (TextUtils.isEmpty(price)) {
            price = "0.00";
        }

        if (tag == Constants.OB_TYPE) {
            return price.replace("¥", "") + "欧花";
        }

        if (mTotalMarketPrice != 0.00) {
            if (!TextUtils.isEmpty(price)) {
                price += "+";
                price += Utils.subTwoNumber(mTotalMarketPrice);
                price += "积分";
            } else {
                price += Utils.subTwoNumber(mTotalMarketPrice);
                price += "积分";
            }
            final List<FirmOrderBean.ProductMapBean> carList = goodsList;
            final FirmOrderBean.ProductMapBean tmpMapBean = carList.get(0);
            if (Double.parseDouble(tmpMapBean.getPrice()) == 0.00) {
                mTvExpressDelivery.setText("运费 ¥0.0");
                price = Utils.subTwoNumber(mTotalMarketPrice);
                price += "积分";
            }
        }
        return price;
    }

    @NotNull
    private String getPrice(double totalPrice) {
        String price = "";
        if (totalPrice != 0.00) {
            price += "¥";
            price += Utils.subTwoNumber(totalPrice);
        }

        if (TextUtils.isEmpty(price)) {
            price = "¥0.00";
        }
        if (tag == Constants.OB_TYPE) {
            return price.replace("¥", "") + "欧花";
        }

        if (mTotalMarketPrice != 0.00) {

            if (!TextUtils.isEmpty(price)) {
                price += "+";
                price += Utils.subTwoNumber(mTotalMarketPrice);
                price += "积分";
            } else {
                price += Utils.subTwoNumber(mTotalMarketPrice);
                price += "积分";
            }

            final List<FirmOrderBean.ProductMapBean> carList = goodsList;
            final FirmOrderBean.ProductMapBean tmpMapBean = carList.get(0);
            if (Double.parseDouble(tmpMapBean.getPrice()) == 0.00) {
                mTvExpressDelivery.setText("运费 ¥0.0");
                price = Utils.subTwoNumber(mTotalMarketPrice);
                price += "积分";
            }

        }
        return price;
    }

    @OnClick({R.id.rl_address, R.id.btn_submit, R.id.rl_full_reduction, R.id.iv_select})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_select://抵扣
                if (isDeIntegral) {
                    if (isDeduct) {
                        isDeduct = false;
                        mTotalPriceW = mTotalPriceW + dkAmt;
                        mTotalMarketPrice = mTotalMarketPrice - deductionIntegral;
                        mIvSelect.setImageResource(R.mipmap.cb_red_normal);
                    } else {
                        String integral = mFirmOrderBean.getKtmap().getIntegral();
                        if (deductionIntegral > Double.parseDouble(integral)) {
                            ToastUtils.showToast("余额积分不足以扣取");
                            return;
                        }
                        isDeduct = true;
                        mTotalPriceW = mTotalPriceW - dkAmt;
                        mTotalMarketPrice = mTotalMarketPrice + deductionIntegral;
                        mIvSelect.setImageResource(R.mipmap.cb_red_select);
                    }
                    mTvRealPayment.setText(getPrice(mTotalPriceW));

                    Log.e("TAG", "mTotalPriceW=" + mTotalPriceW);
                } else {
                    ToastUtils.showToast("没有可抵扣的积分");
                }
                break;
            case R.id.rl_address://地址
                AddressActivity.go(this, 1001, mAid, String.valueOf(mFirmOrderBean.getShaddressMap().getId()));
                break;
            case R.id.rl_full_reduction://地址
                if (activityDialog != null) {
                    activityDialog.toggleDialog();
                } else {
                    if (mActList != null && mActList.size() > 0) {
                        showPopListView();
                    }
                }
                break;
            case R.id.btn_submit:
                if ("-1".equals(mAid)) {
                    ToastUtils.showToast("请添加收货地址");
                    return;
                }
                submitFirmOrder();
                break;
        }
    }

    //提交支付
    private void submitFirmOrder() {
        final String remark = mEtRemark.getText().toString().trim();
        final List<FirmOrderBean.ProductMapBean> carList = goodsList;
        if (carList != null && carList.size() > 0) {
            final FirmOrderBean.ProductMapBean tmpMapBean = carList.get(0);
            List<Map<String, String>> mapList = new ArrayList<>();
            String buylist = "";
            for (int index = 0; index < carList.size(); index++) {
                final FirmOrderBean.ProductMapBean productMapBean = carList.get(index);
                Map<String, String> map = new HashMap<>();
                map.put("productId", String.valueOf(productMapBean.getProduct_id()));
                map.put("attributeId", String.valueOf(productMapBean.getAttribute_id()));
                map.put("freightId", productMapBean.getFreightid() + "");
                map.put("num", productMapBean.getNum() + "");
                mapList.add(map);
                buylist = buylist + productMapBean.getId() + ",";
            }
            if (!TextUtils.isEmpty(buylist)) {
                buylist = buylist.substring(0, buylist.length() - 1);
            }

            String preType = "0";
            String preActivId = "";
            if (isDeIntegral && acListBean != null) {
                if (isDeduct) {
                    preType = "1,2";
                } else {
                    preType = "2";
                }
                preActivId = acListBean.getId() + "";
            } else if (isDeIntegral) {
                if (isDeduct) {
                    preType = "1";
                }
            } else if (acListBean != null) {
                preType = "2";
                preActivId = acListBean.getId() + "";
            }

            Log.e("TAG", "tmpMapBean.getPrice()==" + tmpMapBean.getPrice());
            if (Double.parseDouble(tmpMapBean.getPrice()) == 0.00) {
                //提交积分商品
                mPresenter.submitJf(this, mapList.toString(), mAid, remark, buylist);
                return;
            }

            if (!TextUtils.isEmpty(mCid)) {
                mPresenter.detailSubmit(this, buylist, mapList.toString(), mAid, tmpMapBean.getFreightid() + "", remark, preType, preActivId);
            } else if (!TextUtils.isEmpty(mGid)) {
                mPresenter.detailSubmit(this, "", mapList.toString(), mAid, tmpMapBean.getFreightid() + "", remark, preType, preActivId);
            }
        }
    }

    private void showSportsHarmDialog(final OrderBean orderBean) {

        if (tag == Constants.OB_TYPE) {
            final PayPassDialog dialog = new PayPassDialog(this);
      /*  dialog.getPayViewPass().setForgetText(m);
        dialog.getPayViewPass().setYeText(balace1);*/
            dialog.getPayViewPass().setGone();
            dialog.getPayViewPass()
                    .setPayClickListener(new PayPassView.OnPayClickListener() {
                        @Override
                        public void onPassFinish(String passContent) {

                            mPresenter.onPay(FirmOrderActivity1.this, orderBean.getOrderId(), 0, passContent);
                            dialog.dismiss();
                        }

                        @Override
                        public void onPayClose() {
                            dialog.dismiss();
                            //关闭回调
                        }

                        @Override
                        public void onPayForget() {
                            dialog.dismiss();
                            //点击忘记密码回调
//                        mContext.startActivity(new Intent(mContext, PayPwdActivity.class));
                            EventBus.getDefault().post(new EventBean(Constants.EventCode.JUMP_PAY_PWD, null));

                        }
                    });
        } else {
            PaySelectDialog mSportsHarmDialog = new PaySelectDialog(this, 2);
            final List<FirmOrderBean.ProductMapBean> carList = goodsList;
            final FirmOrderBean.ProductMapBean tmpMapBean = carList.get(0);

            Log.e("TAG", "tmpMapBean.getPrice()=" + tmpMapBean.getPrice());
            Log.e("TAG", "getPriceSpace(mTotalPriceW)=" + getPriceSpace(mTotalPriceW));
            if (Double.parseDouble(tmpMapBean.getPrice()) == 0.00) {
                //积分商品
                mSportsHarmDialog.setData(mTotalMarketPrice + "积分", "");
            } else {
                mSportsHarmDialog.setData(getPriceSpace(mTotalPriceW), orderBean.getKtmap().getBalance());
            }

            mSportsHarmDialog.setOnDialogListener(new PaySelectDialog.onDialogListener() {
                @Override
                public void onConfirm(int type, String payPwd) {
                    payType = type;
                    mPresenter.onPay(FirmOrderActivity1.this, orderBean.getOrderId(), type, payPwd);
                }

                @Override
                public void onCancel() {
                    finish();
                    MyOrderActivity.start(FirmOrderActivity1.this, MyOrderFragment.TYPE_PAY);
                }
            });
            mSportsHarmDialog.toggleDialog();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1001 && resultCode == RESULT_OK && data != null) {
            AddressBean bean = (AddressBean) data.getSerializableExtra("data");
            if (bean == null) {
                ToastUtils.showToast("地址选择失败!");
                return;
            }

            //地址
            mTvName.setText(bean.getConsignee());
            final String contactnumber = bean.getContactnumber();
            final String phonestr = contactnumber.substring(0, 3) + "****" + contactnumber.substring(contactnumber.length() - 4);
            mTvMobile.setText(phonestr);
            if (1 == bean.getIsdefault()) {
                mTvDefault.setVisibility(View.VISIBLE);
            } else {
                mTvDefault.setVisibility(View.GONE);
            }
            mTvEmpty.setVisibility(View.GONE);
            mIvFirmRight.setImageResource(R.mipmap.firm_right_arrow);
            mIvFirmLocation.setVisibility(View.VISIBLE);
            mLlUserInfo.setVisibility(View.VISIBLE);

            String address = "";
            if (bean.getArea0id().equals(bean.getArea1id())) {
                address = bean.getArea1name() + bean.getArea2name() + bean.getXxaddress();
            } else {
                address = bean.getArea0name() + bean.getArea1name() + bean.getArea2name() + bean.getXxaddress();
            }
            mTvAddress.setText(address);
            mAid = String.valueOf(bean.getId());
            mArea0id = Integer.parseInt(bean.getArea0id());
            mArea1id = Integer.parseInt(bean.getArea1id());
            mArea2id = Integer.parseInt(bean.getArea2id());
            hasAddress = true;
            reLoadFreight();
            reloadTotalPrice();
        }
    }

    private void reLoadFreight() {
        if (goodsList.size() > 0) {
            setExpressDelivery();
        }
    }
}
